package com.cherrish.demo.protocol.http;

import com.cherrish.demo.framework.Invocation;
import com.cherrish.demo.framework.URL;
import com.cherrish.demo.register.Register;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;

/**
 * @author cherrish
 * @time 2019-03-20 16:00
 * @name HttpServerHandler
 * @desc:
 */
public class HttpServerHandler {
    public void handle(HttpServletRequest req, HttpServletResponse resp){
        try {
            InputStream inputStream = req.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(inputStream);
            Invocation invocation = (Invocation) ois.readObject();

            //找接口实现类
            String interfaceName = invocation.getInterfaceName();
            URL url = new URL("localhost", 8080);
            Class implClass = Register.get(url, interfaceName);
            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            String result = (String) method.invoke(implClass.newInstance(), invocation.getParams());

            OutputStream outputStream = resp.getOutputStream();

            IOUtils.write("HTTP: " + result, outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
